package com.sav.common.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.sav.common.catalog.User;

@Component
public class UserDAO extends BaseDAO{
	
	public List<String> getRoles(String userName) {
		if (userName == null) return null;
		if (userName.equals("")) return null;
		List<String> roles = new ArrayList<String>();
		PreparedStatement stm = null;
		String query = "SELECT name FROM rolesOfUsers, roles, users WHERE "
				+ "rolesOfUsers.idUser = users.idUser AND rolesOfUsers.idRole = roles.idRole AND users.login = ?";
		try {
				
			stm = getConnection().prepareStatement(query);
			stm.setString(1, userName);
			ResultSet resultSet = stm.executeQuery();
			
			while (resultSet.next()) {
				String role = resultSet.getString("name");
				roles.add(role);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return roles;
	} 
	
	public User getUserByName(String login) {
		if (login == null) return null;
		if (login.equals("")) return null;
		User user = new User();
		
		PreparedStatement stm = null;
		String query = "SELECT * FROM users WHERE login = ?";
		try {
			stm = getConnection().prepareStatement(query);
			stm.setString(1, login);
			ResultSet resultSet = stm.executeQuery();
			if (!resultSet.next()) return null;
			user.setEmail(resultSet.getString("email"));
			user.setEnabled(resultSet.getBoolean("enabled"));
			user.setFullName(resultSet.getString("fullName"));
			user.setIdUser(resultSet.getInt("idUser"));
			user.setLogin(resultSet.getString("login"));
			user.setPassword(resultSet.getString("password"));
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return user;
	}
}
